/*
 * Copyright © Yan Zhenjie. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yanzhenjie.permission;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;

import com.yanzhenjie.permission.target.AppActivityTarget;

import java.lang.reflect.Field;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

/**
 * 这里处理授权的成功或是失败
 *
 * <p>Request permission.</p>
 * Created by Yan Zhenjie on 2017/4/27.
 */
@RequiresApi(api = Build.VERSION_CODES.M)
public class PermissionActivity extends Activity implements Rationale{
    public static String PermissionActionName = "";
//    public static Class PermissionActivityclass = PermissionActivity.class;
    static final String KEY_INPUT_PERMISSIONS = "KEY_INPUT_PERMISSIONS";
    public static Resources pluginResources;

    //变为null 表示已经回调过了。
    private static PermissionResultListener mPermissionListener;

    public static void setPermissionListener(PermissionResultListener permissionListener) {
        mPermissionListener = permissionListener;
    }

    String[] mDeniedPermissions;
    private int mRequestCode;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String[] permissions =mDeniedPermissions= intent.getStringArrayExtra(KEY_INPUT_PERMISSIONS);
        mRequestCode=intent.getIntExtra("RequestCode",0);
        if (mPermissionListener == null || permissions == null)
            finish();
        else{

            boolean showRationale = new AppActivityTarget(this).shouldShowRationalePermissions(mDeniedPermissions);
            RationaleListener mRationaleListener=mPermissionListener.getRationaleListener();
            if (showRationale && mRationaleListener != null)
                mRationaleListener.showRequestPermissionRationale(this, Arrays.asList(mDeniedPermissions),mRequestCode,this);
            else{
                resume();
            }

        }

    }


    @Override
    public void cancel() {

        if(mPermissionListener!=null)
            mPermissionListener.getDefaultRequest().cancel();

        finish();
    }

    @Override
    public void resume() {
        requestPermissions(mDeniedPermissions, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        reApp();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //当销毁的时候 还有mPermissionListener 就认为忘记回调了
        if(mPermissionListener!=null)
            reApp();

    }

    private void reApp(){
        //重新回到app
        //null表示已经回调过了
        if(mPermissionListener!=null) {
            if (mGoSettingRequestPermissions != null && !mGoSettingRequestPermissions.isEmpty()) {
                //再次检查权限。判断授权成功与否。
                List<String> deniedList = new ArrayList<>();
                for (int i = 0; i < mGoSettingRequestPermissions.size(); i++) {
                    String permission = mGoSettingRequestPermissions.get(i);
                    if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                        deniedList.add(permission);
                    }
                }
                if (deniedList.isEmpty()) {
                    callbackSucceed();
                } else {
                    callbackFailed(deniedList);
                }
            }
        }
    }

    private void  callbackFailed(List<String> deniedList){
        if (mPermissionListener != null) {
            mPermissionListener.callbackFailed(mGoSettingRequestPermissions);
            mPermissionListener=null;
            finish();
        }
    }
    private void  callbackSucceed(){
        if (mPermissionListener != null) {
            mPermissionListener.callbackSucceed();
            mPermissionListener=null;
            finish();
        }
    }

    //null 空 就是表示不用去设置请求权限。
    private List<String> mGoSettingRequestPermissions;//需要跑去设置请求权限的
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (mPermissionListener != null) {
//            mPermissionListener.onRequestPermissionsResult(permissions, grantResults);

            List<String> deniedList = new ArrayList<>();
            List<String> hasAlwaysDeniedPermissions = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    if (!shouldShowRequestPermissionRationale(permissions[i])) {

                        hasAlwaysDeniedPermissions.add(permissions[i]);
                    }
                    deniedList.add(permissions[i]);
                }
            }
            //null就是表示不想去设置请求权限。
            boolean isGoSettingRequestPermission=mPermissionListener.getSettingListener()!=null;

            //可以跑去setting请求权限。
            if(isGoSettingRequestPermission){
                //是否需要去setting请求权限
                isGoSettingRequestPermission=!deniedList.isEmpty();//!hasAlwaysDeniedPermissions.isEmpty();
            }


            if (isGoSettingRequestPermission) {
                mGoSettingRequestPermissions = deniedList;// hasAlwaysDeniedPermissions;

                mPermissionListener.getSettingListener().showGoSettingRequestPermissionRationale(this, mGoSettingRequestPermissions, new SettingExecutor(mPermissionListener.getDefaultRequest(), new AppActivityTarget(this), 10000) {//乱写一个requestCode
//                    @Override
//                    public void cancel() {
//                        super.cancel();
//                        callbackFailed(mGoSettingRequestPermissions);
//                    }

                    @Override
                    public void execute() {
                        super.execute();
                    }
                });

            }else{
                mGoSettingRequestPermissions =null;
                if (deniedList.isEmpty()) {
                    callbackSucceed();
                }else { //if(hasAlwaysDeniedPermissions.isEmpty()){//没有永远拒绝。有永远拒绝就还要跑去叫用户开启
                    callbackFailed(deniedList);
                }
            }



        }else{
            finish();
        }



    }

    /**
     * 跟DefaultRequest 的通道
     */
    interface PermissionResultListener {
//        boolean is
        RationaleListener getRationaleListener();
        SettingListener getSettingListener();
        void callbackSucceed();
        void callbackFailed(List<String> deniedList);

        DefaultRequest getDefaultRequest();
//        void onRequestPermissionsResult(@NonNull String[] permissions, @NonNull int[] grantResults);
    }

    // region 替换Resources方案1.2个方案一起来

    @Override
    public Resources getResources() {
        // 重写加载的资源。比如布局文件在哪加载
        if (pluginResources != null) return pluginResources;
        return super.getResources();
    }
    // endregion 替换Resources
    // region 替换Resources方案2  .2个方案一起来
    @Override
    protected void attachBaseContext(Context context) {
        replaceContextResources(context);
        super.attachBaseContext(context);
    }

    /**
     * 使用反射的方式，使用Bundle的Resource对象，替换Context的mResources对象
     *
     * @param
     **/
    public void replaceContextResources(Context context) {
        if (pluginResources == null) return;
        try {
            Field field = context.getClass().getDeclaredField("mResources");
            field.setAccessible(true);
            field.set(context, pluginResources);
            System.out.println("debug:repalceResources succ");
        } catch (Exception e) {
            System.out.println("debug:repalceResources error");
            e.printStackTrace();
        }
    }
    // endregion 替换Resources
}
